package com.yupi.springbootinit.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 *
 * 微信小程序相关业务
 * @Author xingyu Xue
 * @Date 2024/5/2 15:08
 */
@Service
@Slf4j
public class Miniapp {

    @Value("${wx.miniapp.configs[0].appid}")
    private String appid;
    private final WxMaService wxMaService;

    //构造器注入WxMaService 依赖
    @Autowired
    public Miniapp(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }

    /**
     * 判断
     *  返回openid
     */
    public String   isLogin(String code){
        if (StringUtils.isBlank(code)) {
            throw  new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断appid是否存在
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            //向腾讯接口发送code请求，
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            String sessionKey = session.getSessionKey();
            String unionid = session.getUnionid();
            log.info("sessionKey:{}", sessionKey);
            log.info("openid:{}", openid);
            log.info("unionid:{}", unionid);
            return openid;
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }




    }
}
